package com.ccy.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ccy.common.utils.PageUtils;
import com.ccy.common.utils.Query;
import com.ccy.product.dao.CategoryDao;
import com.ccy.product.entity.CategoryBrandRelationEntity;
import com.ccy.product.entity.CategoryEntity;
import com.ccy.product.service.CategoryBrandRelationService;
import com.ccy.product.service.CategoryService;
import com.ccy.product.vo.Catalog2Vo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Transactional
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void removeMenusByIds(List<String> catIds) {

        //TODO 1. 检查当前删除的菜单,是否被别的地方引用
        this.removeByIds(catIds);
    }

    @Override
    public List<Long> findCatlogPath(Long catelogId) {
        List<Long> catlogPath = new ArrayList<>();
        return getPath(catelogId, catlogPath);
    }

    @Override
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);
        //保证冗余字段一致性
        if (StringUtils.isNotEmpty(category.getName())) {
            // 同步更新其他关联数据
            LambdaUpdateWrapper<CategoryBrandRelationEntity> updateWrapper = Wrappers.<CategoryBrandRelationEntity>lambdaUpdate()
                    .set(CategoryBrandRelationEntity::getCatelogName, category.getName())
                    .eq(CategoryBrandRelationEntity::getCatelogId, category.getCatId());
            categoryBrandRelationService.update(updateWrapper);

            // TODO 更新其他关联
        }
    }

    /**
     * 每一个需要缓存的数据我们都来指定要放到哪个名字的缓存(缓存的分区: 推荐按照业务类型进行分区)
     * 代表当前方法的结果需要缓存,如果缓存中有,方法不用调用,如果缓存中没有,会调用方法,并将方法返回的结果放入缓存
     */
    @Cacheable(value = {"categoriesOf1"}, key = "'categoriesOf1'")
    @Override
    public List<CategoryEntity> getLevel1Categories() {
        System.out.println("getLevel1Categories...");
        return categoryDao.selectList(Wrappers.<CategoryEntity>lambdaQuery().eq(CategoryEntity::getParentCid, 0));
    }

    /**
     * 1.空结果缓存,解决缓存穿透
     * 2.设置过期时间(加随机值): 解决缓存雪崩
     * 3.加锁: 解决缓存击穿
     */
    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        /*//先从缓存中查询分类数据
        String categoriesJson = redisTemplate.opsForValue().get("categories");
        //没查到则从数据库查询分类数据
        if (StringUtils.isEmpty(categoriesJson)) {
            return getCatalogJsonFormDbWithRedissonLock();
        }
        //查到则直接返
        return JSON.parseObject(categoriesJson, new TypeReference<Map<String, List<Catalog2Vo>>>() {
        });*/

        return Optional.ofNullable(JSON.parseObject(redisTemplate.opsForValue().get("categories"), new TypeReference<Map<String, List<Catalog2Vo>>>(){}))
                .orElseGet(this::getCatalogJsonFormDbWithRedissonLock);
    }

    /**
     * 从数据查询并封装分类数据(分布式锁redisson方式)
     * 缓存里的数据如何和数据库保持一致??
     * 1).双写模式
     * 2).失效模式
     */
    public Map<String, List<Catalog2Vo>> getCatalogJsonFormDbWithRedissonLock() {

        //占分布式锁,去Redis占坑,创建读锁
        RLock lock = redissonClient.getLock("my-lock");
        lock.lock();
        Map<String, List<Catalog2Vo>> dataFromDb = null;
        try {
            dataFromDb = getDataFromDb();
        } finally {
            lock.unlock();
        }
        return dataFromDb;
    }

    /**
     * 从数据查询并封装分类数据(分布式锁Redis的setExNx方式)
     */
    public Map<String, List<Catalog2Vo>> getCatalogJsonFormDbWithRedisLock() {

        //占分布式锁,去Redis占坑
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock){
            Map<String, List<Catalog2Vo>> dataFromDb = null;
            try {
                dataFromDb = getDataFromDb();
            } finally {
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                //删除锁
                redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
            }
            return dataFromDb;
        }else {
            //加锁失败...重试机制
            //休眠一百毫秒
            try { TimeUnit.MILLISECONDS.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); }
            return getCatalogJsonFormDbWithRedisLock();     //自旋的方式
        }
    }

    /**
     * 从数据查询并封装分类数据(本地锁)
     */
    public Map<String, List<Catalog2Vo>> getCatalogJsonFormDbWithLocalLock() {

        //只要是同一把锁,就能锁住需要这个锁的所有线程
        //1.synchronized(this): springBoot所有组件在容器中都是单例的
        //TODO 本地锁: synchronized, JUC(Lock), 在分布式情况下,想要锁住所有,必须使用分布式锁
        synchronized (this) {
            return getDataFromDb();
        }
    }

    private Map<String, List<Catalog2Vo>> getDataFromDb() {
        String categoriesJson = redisTemplate.opsForValue().get("categories");
        if (StringUtils.isNotEmpty(categoriesJson)) {
            return JSON.parseObject(categoriesJson, new TypeReference<Map<String, List<Catalog2Vo>>>() {
            });
        }
        log.info("缓存未命中,查询数据库,并将数据放入缓存...");
        //获取一级分类id集合
        List<Long> level1Ids = this.getLevel1Categories().stream().map(CategoryEntity::getCatId).collect(Collectors.toList());
        //获取二级分类
        List<CategoryEntity> level2Category = categoryDao.selectList(Wrappers.<CategoryEntity>lambdaQuery().eq(CategoryEntity::getCatLevel, 2));
        //获取三级分类
        List<CategoryEntity> level3Category = categoryDao.selectList(Wrappers.<CategoryEntity>lambdaQuery().eq(CategoryEntity::getCatLevel, 3));

        //组装数据
        HashMap<String, List<Catalog2Vo>> resultMap = new HashMap<>();
        for (Long level1Id : level1Ids) {
            //过滤出该一级分类下的二级分类信息
            List<Catalog2Vo> catalog2Vos = level2Category.stream().filter(l2 -> Objects.equals(l2.getParentCid(), level1Id)).map(l2 -> {
                //过滤出该二级分类下的三级分类
                List<Catalog2Vo.Catalog3Vo> catalog3List = level3Category.stream().filter(l3 -> Objects.equals(l3.getParentCid(), l2.getCatId()))
                        .map(l3 -> new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName())).collect(Collectors.toList());
                //返回封装后的二级分类
                return new Catalog2Vo(level1Id.toString(), catalog3List, l2.getCatId().toString(), l2.getName());
            }).collect(Collectors.toList());
            resultMap.put(level1Id.toString(), catalog2Vos);
        }
        redisTemplate.opsForValue().set("categories", JSON.toJSONString(resultMap), 30, TimeUnit.MINUTES);
        return resultMap;
    }

    // 递归获取catlogPath
    public List<Long> getPath(Long catelogId, List<Long> catlogPath) {
        catlogPath.add(catelogId);
        CategoryEntity entity = this.getById(catelogId);
        if (entity.getParentCid() != 0) {
            getPath(entity.getParentCid(), catlogPath);
        }
        Collections.reverse(catlogPath);
        return catlogPath;
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> categories = this.list();

        //给所有元素设置可选标志

        //2.组成父子的树形结构
        return buildTree(categories);
    }

    private List<CategoryEntity> buildTree(List<CategoryEntity> categories) {
        // 2.1 找到所有一级分类
        List<CategoryEntity> levelOneOfCategory = categories.stream().filter(e -> e.getParentCid() == 0)
                .sorted(Comparator.comparingInt(category -> Objects.isNull(category.getSort()) ? 0 : category.getSort())).collect(Collectors.toList());
        setChildrenByDiGui(levelOneOfCategory, categories);
        return levelOneOfCategory;
    }

    //递归调用设置children
    private void setChildrenByDiGui(List<CategoryEntity> categories, List<CategoryEntity> all) {
        if (CollectionUtils.isNotEmpty(categories)) {
            for (CategoryEntity categoryEntity : categories) {
                List<CategoryEntity> children = all.stream().filter(e -> Objects.equals(e.getParentCid(), categoryEntity.getCatId()))
                        .sorted(Comparator.comparingInt(category -> Objects.isNull(category.getSort()) ? 0 : category.getSort())).collect(Collectors.toList());
                categoryEntity.setChildren(children);
                setChildrenByDiGui(children, all);
            }
        }
    }
}